import { useComponentStore, useStore} from "@/store";
import { List, Space, Input } from "antd";
import { LockOutlined, EyeOutlined, EyeInvisibleOutlined } from "@ant-design/icons";
import styles from "./componentLayer.module.scss"
import classNames from "classnames";
import { useState, type ChangeEvent } from "react";
import SortableContainer from "./dragSortable/sortableContainer";
import SortableItem from "./dragSortable/sortableItem";
export default function ComponentLayer() {
  const {componentList, moveComponent,updateTitle,hiddenComponent, lockComponent} = useComponentStore()
  const {selectedId, setSelectedId} = useStore()
  const [editId, setEditId] = useState("")

  //锁定逻辑
  const handleLock = (id: string) => {
    lockComponent(id)
  }
  //隐藏逻辑
  const handleHide = (id: string,e:React.MouseEvent) => {
    e.stopPropagation()
    hiddenComponent(id)
  }
  //处理编辑
  const handleEdit = (id: string) => {
    //先判断是否被选中
    if (selectedId !== id) {
      setSelectedId(id)
      setEditId("")
      return
    }
    //编辑逻辑
    setEditId(id)
  }
  //处理编辑逻辑
  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    const { value } = e.target
    componentList.forEach(component => {
      if (component.fe_id === editId) {
        component.title = value
      }
    })
    updateTitle(editId, value)
  }
  const chooseStyle = (id: string) => {
    return classNames({
      [styles.chose]: selectedId === id
    })
  }

  const ListWithId =componentList.map((item) => {
    return {...item, id: item.fe_id }
  })

  const handleDragEnd = (oldIndex: number, newIndex: number)=>{
    moveComponent(oldIndex, newIndex)
  }

  return (
    <SortableContainer isDrag={true} items={ListWithId} onDragEnd={handleDragEnd}>
      <List >
        {componentList.map((item, index) => (
          <SortableItem key={item.fe_id} id={item.fe_id}>
             <List.Item key={index} onClick={() => handleEdit(item.fe_id)}>
            {editId !== item.fe_id && <span className={chooseStyle(item.fe_id)}>{item.title}</span>}
            {editId === item.fe_id && <Input
              onBlur={() => setEditId("")} onPressEnter={() => setEditId("")}
              style={{ width: "80%" }} onChange={handleChange}
              type="text" value={item.title}
            />}
            <Space >
              {item.isHidden ? <EyeInvisibleOutlined className={styles.icon} onClick={(e) => handleHide(item.fe_id,e)} /> : <EyeOutlined className={styles.icon} onClick={(e) => handleHide(item.fe_id,e)} />}
              <LockOutlined className={styles.icon} onClick={() => handleLock(item.fe_id)} style={{ color: item.isLocked ? "skyblue" : "" }} />
            </Space>
          </List.Item>
          </SortableItem>
        ))}
      </List>
    </SortableContainer>
  )
}
